package com.android.view.widget.ViewFlipper;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ViewFlipper;


import com.android.R;

import java.util.List;


/**
 */
public abstract class AutoViewFlipper<T> extends ViewFlipper {

    private LayoutInflater factory;
    private View itemView1, itemView2;
    private List<T> infos;
    private int currentIndex = -1;
    private int layout;

    public AutoViewFlipper(Context context, AttributeSet attrs) {
        super(context, attrs);
        factory = LayoutInflater.from(context);
        setFlipInterval(3000);
        setAutoStart(true);
        setInAnimation(getContext(), R.anim.push_up_in);
        setOutAnimation(getContext(), R.anim.push_up_out);
        layout = getItemView();
    }

    public abstract int getItemView();

    public void update(List<T> infos) {
        this.infos = infos;
        if (currentIndex == -1) {
            itemView1 = factory.inflate(layout, this, false);
            itemView2 = factory.inflate(layout, this, false);
            currentIndex = 0;
            addView(itemView1);
            addView(itemView2);
        }
        getCurrentIndex();
        setData(getCurrentView(), currentIndex, infos.get(currentIndex));
    }

    @Override
    public void showNext() {
        currentIndex = getNextViewInfoIndex();
        super.showNext();
        getCurrentIndex();
        setData(getCurrentView(), currentIndex, infos.get(currentIndex));
    }

    public abstract void setData(View view, int postion, T info);

    public View getNextView() {
        if (getCurrentView() == itemView1) {
            return itemView2;
        } else {
            return itemView1;
        }
    }

    public int getCurrentIndex() {
        if (currentIndex > infos.size() - 1) {
            currentIndex = 0;
        }
        return currentIndex;
    }

    public int getNextViewInfoIndex() {
        if (currentIndex + 1 > infos.size() - 1) {
            return 0;
        } else {
            return currentIndex + 1;
        }
    }

}
